package com.glsc.ngateway.platform.controller.costallocation;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.domain.costallocation.IpInfo;
import com.glsc.ngateway.platform.domain.costallocation.SystemComponentCategory;
import com.glsc.ngateway.platform.dto.IpInfoDetailExportDto;
import com.glsc.ngateway.platform.dto.IpInfoDto;
import com.glsc.ngateway.platform.dto.IpInfoQueryDto;
import com.glsc.ngateway.platform.dto.UploadIpInfoDetailDto;
import com.glsc.ngateway.platform.service.costallocation.IpInfoService;
import com.glsc.ngateway.platform.utils.ExcelUtil;
import com.glsc.ngateway.platform.utils.report.ReportUploadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author guoj
 * @description: 应用详情信息
 * @date 2024/8/7 14:40
 */
@RestController
@RequestMapping("/ipInfo")
@Api(value = "IpInfoController", tags = {"应用详情信息"})
public class IpInfoController {
    @Autowired
    private IpInfoService ipInfoService;
    @Value("${export.it}")
    public String itpath;
    @Autowired
    private HttpServletRequest request;



    @GetMapping("/getAllComponent")
    @ApiOperation(value = "查询全部应用类别")
    public PlatformResponse<Map<String, List<SystemComponentCategory>>> getAllComponent() {
        return PlatformResponse.successData(ipInfoService.getAllComponent());
    }

    @PostMapping("/saveOrUpdateCurrAndHistory")
    @ApiOperation(value = "保存应用详情")
    public PlatformResponse<?> save(@RequestBody @Validated IpInfoDto ipInfoDto){
        ipInfoService.saveOrUpdateCurrAndHistory(ipInfoDto);
        return PlatformResponse.success();
    }

    @PostMapping("/listpage")
    @ApiOperation(value = "查询应用详情分页")
    public PlatformResponse<Page<IpInfo>> listpage(@ApiParam(value = "查询条件") @RequestBody IpInfoQueryDto ipInfoQueryDto) {
        return PlatformResponse.successData(ipInfoService.findPage(ipInfoQueryDto));
    }

    @RequestMapping(method = RequestMethod.POST, value = "export")
    @ApiOperation(value = "根据查询条件内容导出应用详情分摊明细", notes = "根据查询条件内容导出应用详情分摊明细")
    public ResponseEntity<byte[]> exportServerFullOutPut(@ApiParam(value = "查询条件") @RequestBody IpInfoQueryDto ipInfoQueryDto) throws Exception {

        List<IpInfoDetailExportDto> result = ipInfoService.queryExportData(ipInfoQueryDto);
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "应用详情分摊明细").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "应用详情分摊明细.xlsx";
        //String fileName = "D:\\guoju\\downloadfile" + "应用详情分摊明细.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        in.read(bytes);

        //使用URLEncoder来防止文件名乱码或者读取错误
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("应用详情分摊明细.xlsx", "utf-8"));
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }


    @PostMapping("/upload")
    @ApiOperation(value = "导入应用详情数据", notes = "导入应用详情数据")
    public PlatformResponse<?> uploadPartDetail(@RequestPart("file") MultipartFile file) throws IOException {
        ReportUploadContext<UploadIpInfoDetailDto, String> context = ipInfoService.uploadUploadIpInfoDetail(file);
        return context.isCheckPass() ? PlatformResponse.successData(context.getReadRes()) : PlatformResponse.failedMsg(String.join(",", context.getCheckRes()));
    }
}
